// Copyright 2010 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.api.ads.common.lib.utils;

import java.lang.reflect.Field;

/**
 * A utility class for handling choice objects.
 *
 * @author Adam Rogal
 */
public final class ChoiceUtils {

  /**
   * Default constructor.
   */
  public ChoiceUtils() {}

  /**
   * Gets the value of the choice object without having to inspect each
   * field.
   *
   * @param obj the choice object to get the value from
   * @return the value of the choice
   * @throws IllegalArgumentException if {@code obj == null}
   * @throws IllegalAccessException if the non-null field cannot be accessed in
   *     the choice object
   */
  public Object getValue(Object obj)
      throws IllegalArgumentException, IllegalAccessException {
    if (obj == null) {
      throw new IllegalArgumentException("Choice object cannot be null.");
    }
    Field[] fields = obj.getClass().getDeclaredFields();
    for (Field field : fields) {
      if (!(field.getName().equals("typeDesc") || field.getName().startsWith("__"))) {
        field.setAccessible(true);
        if (field.get(obj) != null) {
          return field.get(obj);
        }
      }
    }
    return null;
  }
}
